/**
 * Created by artheru on 2016/11/4.
 */

import "regenerator-runtime";
//import 'babel-polyfill';
import 'whatwg-fetch';

import sprintf from "sprintf";
import { redirectTemporarily } from "utils";

const baseAPI = "%s"

async function post(api, data) {
    let response = await self.fetch(sprintf(baseAPI, api), {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'text/plain'
        },
        body: JSON.stringify(data?data:{})
    });
    let pck = await response.json();
    if (pck.error)
        throw pck.error;
    return pck;
};

async function get(api, data) {
    let response;
    if (data)
        response = await fetch(sprintf(baseAPI, sprintf("%s?%s", api, $.param(data))));
    else
        response = await fetch(sprintf(baseAPI, sprintf("%s", api)));
    let pck = await response.json();
    if (pck.error)
        throw pck.error;
    return pck;
};

const wrap = fn => ((...args) => fn(...args).catch(e => {
    console.log("backend call failed:", e);
    alert(e);
    console.log(e.stack);
    if (handler[e.toString()])
        handler[e.toString()](e);
    else
        throw e;
}));

let handler = {

    "notValidToken": () => redirectTemporarily("/login/?redirect=" + encodeURIComponent(window.location)),
};

function thing(what){
    return {
        get: wrap(async (id)=>{
            let xml=await get(sprintf(what,"get"));
            show(xml);
        }),
    }
}

export default {
    user:{ get: wrap(async (uid)=>(await get("http://test.utbon.com/api/im/getUserInfo.ashx", { uid }))) },
    tokenify: wrap(async(token)=>(await get("http://test.utbon.com/api/im/tokenify.ashx?token="+token)).uid)
}

